const app = getApp();
import uploadFile from "../../utils/upload.js";
import { throttle, back } from "../../utils/util";
import {
  readClockApi,
  getCurrentPlanApi,
  getClockCountApi,
  getSloganApi,
  getLastTimeClockApi,
  getMotionsForAppApi,
  getLastSportRecordApi,
  sportClockApi,
  noLongerRemindApi,
} from "../../api/app.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentPlanData: null, // 当前计划数据
    isShowRemindModal: false, // 是否显示提醒弹窗
    checked: false, // 是否勾选不再提醒
    currentTab: 2, // 当前tab 1-阅读打卡 2-运动打卡
    CustomBar: app.globalData.CustomBar,
    // 阅读打卡
    slogan: "", // 阅读打卡标语
    clockinDay: 0, // 阅读打卡次数
    bookType: "", // 书籍类型
    bookId: "", // 书目id
    selectedBook: null, // 已选择的书籍
    maxHour: 12, // 阅读时长小时最高值
    maxMin: 59, // 阅读时长分钟最高值
    maxScond: 59, // 阅读时长秒最高值
    timeSelect: [], // 选择器
    timeValue: [0, 30], // 选择器值
    pageStart: "1",
    pageEnd: "",
    node: "", // 笔记内容
    fileType: "", // 上传文件类型
    photos: [], // 图片
    photoMaxCount: 4, // 最多上传图片数量
    video: {}, // 视频
    showRecite: false, // 显示录音
    reciteTime: 0, // 当前录音时长
    reciteStatus: 0, // 1正在录音，2取消录音，3完成录音
    reciteTimeMax: 300, // 最大录音时长s
    recorderManager: null, // 录音管理器,
    intervalId: null, // 计时器
    audio: {},
    audioContext: null, //音频管理器
    audioStatus: 0, // 0停止，1正在播放
    selectFinish: false, //完成选择书籍
    // 运动打卡
    sportId: "", // 运动id
    selectedMotion: null, // 选择的运动
    motionList: [], // 运动项具体数据
    motionItems: ["滑雪", "蹦极"], // 运动打卡-运动项
    motionValue: -1, // 运动打卡选择器值
    motionNumber: 20, // 运动次数
    motionTimes: [], // 运动时长选项
    motionTime: [0, 30, 0], // 运动时长
    motionClockinDay: 0, // 运动打卡天数
    motionSlogan: "", // 运动打卡标语
    mo_node: "", // 运动笔记内容
    mo_fileType: "", // 上传文件类型
    mo_photos: [], // 图片
    mo_photoMaxCount: 4, // 最多上传图片数量
    mo_video: {}, // 运动打卡视频
    mo_audio: {}, // 运动打卡音频
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const from = options.from || "";
    const { windowHeight } = wx.getSystemInfoSync();
    const hours = [],
      mins = [],
      scond = [];
    for (let i = 0; i <= this.data.maxHour; i++) {
      hours.push(`${i}小时`);
    }
    for (let i = 0; i <= this.data.maxMin; i++) {
      mins.push(`${i}分钟`);
    }
    for (let i = 0; i <= this.data.maxScond; i++) {
      scond.push(`${i}秒`);
    }
    const timeSelect = [hours, mins];
    const motionTimes = [hours, mins, scond];
    this.setData({
      windowHeight,
      timeSelect,
      motionTimes,
      currentTab: Number(options.currentTab) || 1,
      from,
    });
    this.init();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.selectFinish) {
      this.getClock();
      this.setData({
        selectFinish: false,
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.share(this, {
      title: "我正在「云上书院」阅读打卡，让孩子打卡养成阅读好习惯吧",
      imageUrl: "",
    });
  },

  // 初始化
  init() {
    this.getMotionsForApp();
    this.getSlogan("read");
    this.getClockCount("read");
    this.getSlogan("sport");
    this.getClockCount("sport");
    this.getCurrentPlan();
    this.getClock();
  },
  // 提交运动打卡
  async motionClockin() {
    try {
      const experience = this.data.mo_node;
      const imageFids = this.data.mo_photos.map((item) => item.fid);
      const sportCount = this.data.selectedMotion.countIsNeed
        ? this.data.motionNumber
        : 0;
      const sportDuration =
        parseInt(
          this.data.motionTime[0] * 60 * 60 +
            this.data.motionTime[1] * 60 +
            this.data.motionTime[2]
        ) || 0;
      const sportId = this.data.selectedMotion.sportId;
      const videoFid = this.data.mo_video.fid || "";
      const voiceFid = this.data.mo_audio.fid || "";

      const res = await sportClockApi(
        experience,
        imageFids,
        sportCount,
        sportDuration,
        sportId,
        videoFid,
        voiceFid
      );
      if (res.code == 200 && res.data) {
        app.toast("打卡成功");
        //跳转
        const data = {
          slogan: this.data.motionSlogan,
          ...res.data,
        };
        setTimeout(() => {
          wx.redirectTo({
            url: `/appPages/clockin/clockin-successfully/index?data=${JSON.stringify(
              data
            )}&from=${this.data.from}&clokinType=${this.data.currentTab}`,
          });
        }, 500);
      }
    } catch (error) {
      console.log(error);
    }
  },
  // 提交阅读打卡
  clockin() {
    const that = this;
    const pageStart = that.data.pageStart - 0; // 转数字
    const pageEnd = that.data.pageEnd - 0; // 同上
    if (!that.data.selectedBook.sourceId) {
      app.toast("请选择需要打卡的书籍");
      return;
    }
    if (that.data.timeValue.length == 0) {
      app.toast("请选择阅读时长");
      return;
    }
    if (pageStart <= 0 || pageEnd <= 0) {
      app.toast("请填写正确的阅读页数");
      return;
    }
    if (pageEnd < pageStart) {
      app.toast("结束页数必须大于开始页数，请重新输入");
      return;
    }
    const readTime = that.data.timeValue[0] * 60 + that.data.timeValue[1];
    const addReadComment = [];
    if (that.data.fileType == "photo") {
      that.data.photos.map((item) => {
        addReadComment.push({
          fileType: 1,
          fid: item.fid,
        });
      });
    } else if (that.data.fileType == "video") {
      addReadComment.push({
        fileType: 3,
        fid: that.data.video.fid,
        coverUrl: that.data.video.cover,
      });
    } else if (that.data.fileType == "audio") {
      addReadComment.push({
        fileType: 2,
        fid: that.data.audio.fid,
      });
    }
    readClockApi(
      that.data.node,
      String(that.data.selectedBook.sourceId),
      pageStart,
      pageEnd,
      that.data.bookType,
      readTime,
      addReadComment
    )
      .then((res) => {
        app.toast("打卡成功");
        //跳转
        const data = {
          slogan: this.data.slogan,
          selectedBook: this.data.selectedBook,
          pageStart: this.data.pageStart,
          pageEnd: this.data.pageEnd,
          timeValue: this.data.timeValue,
          ...res.data,
        };
        setTimeout(() => {
          wx.redirectTo({
            url: `/appPages/clockin/clockin-successfully/index?data=${JSON.stringify(
              data
            )}&from=${this.data.from}&clokinType=${this.data.currentTab}`,
          });
        }, 500);
      })
      .catch((err) => {
        console.log(err);
      });
  },
  // 获取打卡天数
  async getClockCount(type) {
    try {
      // read或空表示阅读打卡，sport表示运动打卡
      const res = await getClockCountApi(type);
      if (res) {
        if (type == "read") {
          this.setData({
            clockinDay: res.data,
          });
        } else {
          this.setData({
            motionClockinDay: res.data,
          });
        }
      }
    } catch (error) {
      console.log(error);
    }
  },
  // 获取标语
  async getSlogan(type) {
    try {
      // read或空表示阅读打卡，sport表示运动打卡
      const res = await getSloganApi(type);
      if (res) {
        if (type == "read") {
          this.setData({
            slogan: res.data,
          });
        } else {
          this.setData({
            motionSlogan: res.data,
          });
        }
      }
    } catch (error) {
      console.log(error);
    }
  },
  // 获取当前计划
  async getCurrentPlan() {
    try {
      // 何时传true何时传false
      const res = await getCurrentPlanApi({
        excludeFinish: true,
      });
      if (res.code == 200) {
        this.setData({
          currentPlanData: res.data,
          isShowRemindModal: res.data && res.data.isRemind,
        });
      }
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  },
  // 获取运动项选择列表
  async getMotionsForApp() {
    try {
      const res = await getMotionsForAppApi();
      if (res.code == 200 && res.data) {
        let sportId = "";
        res.data.forEach((item) => {
          if (item.isLast) {
            sportId = item.sportId;
          }
        });
        this.setData({
          motionItems: res.data.map((item) => item.sportName),
          motionList: res.data,
          sportId,
        });
        if (sportId) {
          this.getLastSportRecord(sportId);
        }
      }
    } catch (error) {
      console.log(error);
    }
  },
  // 获取最近一次运动打卡记录
  async getLastSportRecord(sportId) {
    try {
      const res = await getLastSportRecordApi(sportId);
      if (res.data) {
        let hours = parseInt(res.data.sportDuration / 60 / 60);
        let mins = parseInt((res.data.sportDuration / 60) % 60);
        let scond = parseInt(res.data.sportDuration % 60);
        this.setData({
          selectedMotion: res.data,
          motionValue: this.data.motionItems.indexOf(res.data.sportName),
          motionNumber: res.data.sportCount,
          motionTime: [hours, mins, scond],
        });
      }
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  },
  // 获取最近一次阅读打卡记录
  getClock() {
    const that = this;
    const data = {};
    that.data.bookId && (data.bookId = that.data.bookId);
    that.data.bookType && (data.btype = that.data.bookType);
    getLastTimeClockApi(data)
      .then((res) => {
        // 阅读页数
        let pageStart = "1",
          pageEnd = "";
        if (res.data.readTotalTime > 0) {
          let page = res.data.endPage - res.data.beginPage;
          if (page < 0) {
            page = 5;
          }
          pageStart = res.data.endPage + 1;
          pageEnd = pageStart + page;
        }
        // 阅读时长
        const hour = Math.floor(res.data.readTime / 60) || 0;
        const min = res.data.readTime - hour * 60 || 30;
        that.setData({
          pageStart,
          pageEnd,
          bookType: res.data.btype,
          selectedBook: {
            sourceId: res.data.bookId,
            bookName: res.data.bookName,
            cover: res.data.covers,
            readStudentCount: res.data.readStudentCount,
            readTotalTime: res.data.readTotalTime,
          },
          timeValue: [hour, min],
        });
      })
      .catch((err) => {
        console.log(err);
        that.setData({
          selectedBook: null,
        });
      });
  },
  // 显示modal
  showModal() {
    if (this.data.checked) {
      this.noLongerRemin();
    }
    this.setData({
      isShowRemindModal: !this.data.isShowRemindModal,
    });
  },
  // 监听复选框改变
  changeChecked() {
    this.setData({
      checked: !this.data.checked,
    });
  },
  // 切换Tab
  changeTab(e) {
    let tab = e.currentTarget.dataset.index;
    this.setData({
      currentTab: tab,
    });
  },
  // 返回事件
  backHandle() {
    const that = this;
    if (that.data.reciteStatus !== 1) {
      back();
      return;
    }
    wx.showModal({
      title: "温馨提示",
      content: "您正在录音，确认要退出吗？",
      success(res) {
        if (res.confirm) {
          that.setData({
            reciteTime: 0,
            reciteStatus: 2,
            showRecite: false,
          });
          that.data.recorderManager.stop();
          back();
        }
      },
    });
  },

  // 上传文件
  upload(file, type) {
    return uploadFile({
      filePath: file,
      formData: {
        type,
      },
    });
  },

  // 选择阅读时长
  selectTime(e) {
    const timeValue = e.detail.value;
    if (timeValue[0] + timeValue[1] <= 0) {
      app.toast("阅读时长不能为0");
      return;
    }
    this.setData({
      timeValue,
    });
  },

  // 选择照片
  async selectPic() {
    const isRead = this.data.currentTab == 1;
    const photosLength = isRead
      ? this.data.photos.length
      : this.data.mo_photos.length;
    const curPhotos = isRead ? this.data.photos : this.data.mo_photos;
    if (photosLength >= this.data.photoMaxCount) {
      app.toast(`最多上传${this.data.photoMaxCount}张图片`);
      return;
    }
    try {
      const tmpPhotos = await wx.chooseImage({
        count: this.data.photoMaxCount - photosLength,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
      });
      const tempFilePaths = tmpPhotos.tempFilePaths;

      for (let i = 0; i < tempFilePaths.length; i++) {
        let uploadResult = await this.upload(tempFilePaths[i], "image");
        if (uploadResult.code != 200) {
          app.toast("部分图片上传失败，请重试");
        } else {
          curPhotos.push({
            fid: uploadResult.fid,
            previewUrl: tempFilePaths[i],
            url: uploadResult.viewUrl,
          });
        }
      }
      if (isRead) {
        this.setData({
          fileType: "photo",
          photos: curPhotos,
        });
      } else {
        this.setData({
          mo_fileType: "photo",
          mo_photos: curPhotos,
        });
      }
    } catch (err) {
      console.log(err);
    }
  },

  // 删除照片
  delPhoto(e) {
    const isRead = this.data.currentTab == 1;
    const index = e.mark.index;
    let photos = isRead ? this.data.photos : this.data.mo_photos;
    photos.splice(index, 1);
    if (photos.length == 0) {
      isRead
        ? this.setData({
            fileType: "",
            photos: [],
          })
        : this.setData({
            mo_fileType: "",
            mo_photos: [],
          });
      return;
    }
    isRead
      ? this.setData({
          photos,
        })
      : this.setData({
          mo_photos: photos,
        });
  },

  // 预览图片
  previewPhoto(e) {
    const index = e.mark.index;
    const photos = this.data.photos.map((item) => item.previewUrl);
    wx.previewImage({
      current: photos[index], // 当前显示图片的http链接
      urls: photos, // 需要预览的图片http链接列表
    });
  },

  // 选择视频
  selectVideo() {
    const isRead = this.data.currentTab == 1;
    const that = this;
    wx.chooseVideo({
      sourceType: ["album", "camera"],
      maxDuration: 15,
      camera: "back",
      success(res) {
        wx.openVideoEditor({
          filePath: res.tempFilePath,
          success(editRes) {
            // 不能超过两分钟
            if (editRes.duration > 120000) {
              app.toast("视频不能超过2分钟，请重新选择");
              return;
            }

            that.upload(editRes.tempFilePath, "vedio").then((uploadRes) => {
              if (uploadRes.code != 200) {
                app.toast("上传失败，请重试");
                return;
              }
              if (isRead) {
                that.setData({
                  fileType: "video",
                  video: {
                    fid: uploadRes.fid,
                    previewUrl: editRes.tempFilePath,
                    url: uploadRes.viewUrl,
                    cover: editRes.tempThumbPath,
                  },
                });
              } else {
                that.setData({
                  mo_fileType: "video",
                  mo_video: {
                    fid: uploadRes.fid,
                    previewUrl: editRes.tempFilePath,
                    url: uploadRes.viewUrl,
                    cover: editRes.tempThumbPath,
                  },
                });
              }
            });
            // 上传封面
            that.upload(editRes.tempThumbPath, "image").then((uploadRes) => {
              if (uploadRes.code != 200) {
                app.toast("上传失败，请重试");
                return;
              }
              const video = isRead ? that.data.video : that.data.mo_video;
              video.cover = uploadRes.viewUrl;
              isRead
                ? that.setData({
                    fileType: "video",
                    video: video,
                  })
                : that.setData({
                    mo_fileType: "video",
                    mo_video: video,
                  });
            });
          },
        });
      },
    });
  },

  // 预览视频
  previewVideo() {
    const isRead = this.data.currentTab == 1;
    const curVideo = isRead ? this.data.video : this.data.mo_video;
    if (!curVideo) {
      app.toast("未上传任何视频");
      return;
    }
    wx.previewMedia({
      sources: [
        {
          type: "video",
          url: curVideo.previewUrl,
          poster: curVideo.cover,
        },
      ],
    });
  },

  // 删除视频
  delVideo() {
    const that = this;
    const isRead = this.data.currentTab == 1;
    wx.showModal({
      title: "温馨提示",
      content: "确定要删除此视频吗？",
      success(res) {
        if (res.confirm) {
          isRead
            ? that.setData({
                fileType: "",
                video: {},
              })
            : that.setData({
                mo_fileType: "",
                mo_video: {},
              });
        }
      },
    });
  },

  // 显示录音
  showRecite() {
    this.setData({
      showRecite: true,
    });
  },

  // 隐藏录音
  onCloseRecite() {
    const that = this;
    if (this.data.reciteStatus == 1) {
      wx.showModal({
        title: "温馨提示",
        content: "您正在录音，确认要退出吗？",
        success(res) {
          if (res.confirm) {
            that.setData({
              reciteTime: 0,
              reciteStatus: 2,
              showRecite: false,
            });
            that.data.recorderManager.stop();
          }
        },
      });
      return;
    }
    this.setData({
      showRecite: false,
    });
  },

  // 检查是否授权录音
  isAuth() {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.getSetting().then((res) => {
        if (!res.authSetting["scope.record"]) {
          wx.authorize({
            scope: "scope.record",
            success() {
              return resolve(true);
            },
            fail(res) {
              app.toast("请先同意录音授权");
              that.setData({
                showAuth: true,
              });
              return resolve(false);
            },
          });
        } else {
          return resolve(true);
        }
      });
    });
  },

  // 打开设置
  openSetting() {
    const that = this;
    wx.openSetting({
      success() {
        that.setData({
          showAuth: false,
        });
      },
    });
  },

  // 开始录音
  startRecite: throttle(function () {
    this.isAuth().then((res) => {
      if (!res) {
        return;
      }
      this.reciting();
    });
  }),

  // 正在录音
  reciting() {
    const that = this;
    const isRead = this.data.currentTab == 1;
    const recorderManager = wx.getRecorderManager();
    recorderManager.onError((err) => {
      console.log(err);
    });
    recorderManager.onStart(() => {
      let intervalId = setInterval(() => {
        that.setData({
          reciteTime: that.data.reciteTime + 1,
        });
        if (that.data.reciteTime >= that.data.reciteTimeMax) {
          this.stopReciting();
        }
      }, 1000);
      that.setData({
        intervalId,
      });
    });
    // 监听录音暂停
    recorderManager.onPause((res) => {
      this.stopReciting();
    });
    recorderManager.onStop((res) => {
      clearInterval(that.data.intervalId);
      that.setData({
        intervalId: null,
        showRecite: false,
      });
      // 取消录音
      if (that.data.reciteStatus == 2) {
        return;
      }
      // 完成录音
      wx.showLoading({
        title: "正在上传...",
        mask: true,
      });
      that.upload(res.tempFilePath, "audio").then((uploadRes) => {
        wx.showToast({
          title: "上传成功",
        });
        if (isRead) {
          that.setData({
            fileType: "audio",
            audio: {
              fid: uploadRes.fid,
              duration: Math.round(res.duration / 1000),
              previewUrl: res.tempFilePath,
              url: uploadRes.viewUrl,
            },
          });
        } else {
          that.setData({
            mo_fileType: "audio",
            mo_audio: {
              fid: uploadRes.fid,
              duration: Math.round(res.duration / 1000),
              previewUrl: res.tempFilePath,
              url: uploadRes.viewUrl,
            },
          });
        }
      });
      that.setData({
        reciteTime: 0,
        reciteStatus: 0,
      });
    });
    const options = {
      duration: that.data.reciteTimeMax * 1000,
      sampleRate: 11025,
      numberOfChannels: 2,
      encodeBitRate: 48000,
      format: "mp3",
    };
    recorderManager.start(options);
    that.setData({
      reciteStatus: 1,
      recorderManager,
    });
  },

  // 停止录音
  stopReciting() {
    this.setData({
      reciteStatus: 3,
    });
    this.data.recorderManager.stop();
  },

  // 播放音频
  playAudio() {
    const that = this;
    const isRead = this.data.currentTab == 1;
    let audioContext = null;
    if (that.data.audioContext) {
      audioContext = that.data.audioContext;
      if (that.data.audioStatus == 0) {
        audioContext.play();
        return;
      }
      audioContext.stop();
      return;
    }
    audioContext = wx.createInnerAudioContext();
    audioContext.onError((err) => {
      console.log(err);
      app.toast("播放失败，请重试");
    });
    audioContext.onPlay(() => {
      that.setData({
        audioStatus: 1,
      });
    });
    audioContext.onStop(() => {
      that.setData({
        audioStatus: 0,
      });
    });
    audioContext.onEnded(() => {
      that.setData({
        audioStatus: 0,
      });
    });
    audioContext.src = isRead
      ? that.data.audio.previewUrl
      : that.data.mo_audio.previewUrl;
    that.setData({
      audioContext,
    });
    audioContext.play();
  },

  // 删除音频
  delAudio() {
    const that = this;
    const isRead = this.data.currentTab == 1;
    wx.showModal({
      title: "温馨提示",
      content: "确定要删除此音频吗？",
      success(res) {
        if (res.confirm) {
          isRead
            ? that.setData({
                fileType: "",
                audio: {},
                audioContext: null,
              })
            : that.setData({
                mo_fileType: "",
                mo_audio: {},
                audioContext: null,
              });
        }
      },
    });
  },

  // 选择书籍
  selectBook() {
    wx.navigateTo({
      url: `/appPages/clockin/select-book/index`,
    });
  },

  // 跳转到打开日历
  toCalendar() {

  },

  // 选择运动项
  selectMotion(e) {
    console.log(e);
    const index = e.detail.value || e.currentTarget.dataset.index;
    this.setData({
      selectedMotion: this.data.motionList[index],
      motionValue: index,
      sportId: this.data.motionList[index].sportId,
    });
  },
  // 选择运动时长
  selectMotionTime(e) {
    const motionTime = e.detail.value;
    if (motionTime[0] + motionTime[1] + motionTime[2] <= 0) {
      app.toast("运动时长不能为0");
      return;
    }
    this.setData({
      motionTime,
    });
  },
  // 跳转到计时工具
  toTimer() {
    const motionName = this.data.motionItems[this.data.motionValue];
    const motionNumber = this.data.selectedMotion.countIsNeed
      ? this.data.motionNumber
      : 0;
    const unit = this.data.selectedMotion.countUnit || "";
    wx.navigateTo({
      url: `/appPages/clockin/timer/index?motionName=${motionName}&motionNumber=${motionNumber}&unit=${unit}`,
    });
  },
  // 跳转到打卡计划
  toPlan() {
    wx.navigateTo({
      url: `/appPages/clockin/clockin-plan/index`,
    });
  },
  // 不再提醒
  async noLongerRemin() {
    try {
      const res = await noLongerRemindApi();
    } catch (error) {
      console.log(error);
    }
  },
});
